# coding: utf-8


import os
import time
import uuid
import urllib2
from sys import argv
from ConfigParser import ConfigParser as Parser
from utils.jktest import *

'''
技能商城回归测试: 技能商城体验测试
'''

class CASE():
    def __init__(self, skillCode, sentence, checks):
        self.skillCode = skillCode
        self.sentence = sentence
        self.checks = checks
        self.url = ""
        self.response = ""
        self.result = []

def get_url(skillCode, sentence, uuid):
    # print sentence
    return "%s/manage/skill/probation?udid=%s&skillCode=%s&sentence=%s" % (Server, uuid, skillCode, urllib2.quote(sentence))

def get_reponse(case):
    # print case.url
    return urllib2.urlopen(case.url).read()

def run(case_file):
    case_list = []
    skillCode_last = ""
    uuid_last = ""
    NUM_skill = 0

    skill_name = ''
    for ln in open(case_file):
        ln = ln.strip()
        if not ln:
            continue
        if ln.startswith('#'):
            skill_name = ln.strip().split('#')[1].strip()
        else:
            ln_parts = ln.split('\t')
            sentence, skillCode = ln_parts[0].split(';')

            if '=' in skillCode:
                skillCode = skillCode.split('=')[1]

            if skillCode_last != skillCode:
                NUM_skill += 1
                skillCode_last = skillCode
                uuid_last = uuid.uuid4()

            checks = ln_parts[-1]
            case = CASE(skillCode, sentence, checks)
            case.url = get_url(skillCode_last, sentence, uuid_last)
            case.response = get_reponse(case)
            case.response = case.response.replace('\\"', '"')
            case.result = get_unmatch_list(case.checks, case.response)
            case_list.append(case)
            if case.result:
                print "Failed: [技能: %s] >>>> 语料: %s" % (skill_name, case.sentence)
            # else:
            #     print "Passed: %s" % case.sentence
    print "Skill_Num: %d" % NUM_skill
    log(case_list)


def log(case_list):
    total = len(case_list)
    fail = 0
    with open(Log, 'w') as log:
        for case in case_list:
            if case.result:
                fail += 1
                lg  = "用例: %s\n" % case.sentence
                lg += "\n%s\n" % case.url
                lg += "不匹配:\n%s\n\n" % "\n".join(case.result)
                lg += "响应:\n%s\n" % case.response
                lg += "+" * 80 + "\n"
                log.write(lg)
            else:
                lg  = "用例 : %s\n" % case.sentence
                lg += "URL :\n%s\n" % case.url
                lg += "+" * 80 + "\n"
                log.write(lg)
    print '-' * 40
    print 'Server : %s' % Server
    print '-' * 40
    print "Case total: %d\tpass:%d fail:%d" % (total, total-fail, fail)
    print '-' * 40
    if fail == 0:
        print ">>>>>>>> All Cases Pass! <<<<<<<<<<"
    else:
        print "Details: [%s]" % Log
        print '-' * 40

def show_elapsed_time(begin):
    fr = time.strftime("%H:%M:%S", time.localtime(begin))
    to = time.strftime("%H:%M:%S", time.localtime(time.time()))
    elapsed_sec = time.time() - begin

    m = elapsed_sec / 60
    s = elapsed_sec % 60
    print "Elapsed_Time: %d'%d'' (%s ~ %s)" % (m, s, fr, to)

def get_configs(env, conf_file='conf/usk_shop.conf'):
    config = Parser()
    config.read(conf_file)
    uri = config.get(env, 'server').strip()
    case_file = config.get(env, 'case_file').strip()
    out_dir = config.get('log', 'out_dir').strip()

    return (uri, case_file, out_dir)



if __name__ == '__main__':
    # 输入一个参数, online / uat, 自动从conf/usk_shop.conf中读取相关配置.
    env = "online"
    if len(argv) > 1:
        env = argv[1].strip()
    if env.lower() != 'uat':
        env = "online"

    Server, Case_File, Out_Dir = get_configs(env)
    Log = os.path.join(Out_Dir, "usk_shop_%s.log" % env)

    print "Run test on : [%s], suit: [%s]" % (Server, Case_File)
    print "-" * 80

    begin = time.time()
    run(Case_File)
    show_elapsed_time(begin)